<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .demo {
        font-family: sans-serif;
        border: 1px solid #eee;
        border-radius: 2px;
        padding: 20px 30px;
        margin-top: 1em;
        margin-bottom: 40px;
        user-select: none;
        overflow-x: auto;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>

    <script src="../lib/vue3.js"></script>
    <script>
      /**
       * 用于收集订阅的消息
       *
       *    {
       *      消息名字: 消息回调函数的集合
       *    }
       */
      const map = {};

      // 订阅
      //    on('消息名字', 'callback 消息回调函数')
      function on(message, fn) {
        if (map[message]) {
          map[message].push(fn);
        } else {
          map[message] = [fn];
        }
      }

      // 发布
      //    publish('消息名字', '传递给该消息回调函数的参数')
      function publish(message, payload) {
        if (map[message]) {
          map[message].forEach((cb) => {
            cb();
          });
        }
      }

      // 取消订阅
      function off(message) {
        if (map[message]) {
          map[message] = [];
        }
      }

      const app = Vue.createApp({
        template: `
          <div class="demo">
            <Hello v-if="isShow" /> 
            <hr />
            <button @click="isShow = !isShow">Toggle</button>
          </div>
        `,

        data() {
          return {
            isShow: true,
          };
        },
      });

      app.component("Hello", {
        template: `
          <div>
            Hello, {{ count }}
          </div>
        `,

        data() {
          return {
            count: 1,
          };
        },

        methods: {
          increment() {
            this.count++;
          },

          handleClick() {
            console.log("click");
          },
        },

        mounted() {
          // this.timer = setInterval(() => {
          //   console.log("interval");
          // }, 1000);

          window.addEventListener("click", this.handleClick);

          // 消息的订阅
          on("increment", () => {
            console.log("increment 消息被触发了");
            this.count++;
          });
        },

        unmounted() {
          // 清理工作
          //    1. 清理定时器
          //    2. 全局的事件绑定的清理（v-on绑定的事件是无需清理的）
          //    3. 消息订阅的取消
          clearInterval(this.timer);

          window.removeEventListener("click", this.handleClick);

          off("increment");
        },
      });

      app.mount("#app");
    </script>
  </body>
</html>
